/**
 * 用户登录记录
 */

const router = require('koa-router')()
const UserLogin = require('./../models/userLoginSchema')
const util = require('./../utils/util')

router.prefix('/userLogins')

// 获取所有用户本月登录记录数量和上月登录记录数量
router.get('/count', async (ctx) => {
    try {
        const now = new Date();
        const thisMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
        const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        
        // 获取本月登录记录数量
        const thisMonthCount = await UserLogin.countDocuments({
            lastLoginTime: { $gte: thisMonthStart }
        });
        
        // 获取上月登录记录数量
        const lastMonthCount = await UserLogin.countDocuments({
            lastLoginTime: { 
                $gte: lastMonthStart, 
                $lt: thisMonthStart 
            }
        });
        
        ctx.body = util.success({
            thisMonthCount,
            lastMonthCount
        }, '获取登录记录数量成功');
    } catch (error) {
        ctx.body = util.fail(error.message, '获取登录记录数量失败');
        console.error('获取登录记录数量失败:', error);
    }
})

module.exports = router